<template>
  <div class="container">
    <!--工具栏-->
    <div
      class="toolbar"
      style="float: left; padding-top: 10px; padding-left: 15px"
    >
      <el-form :inline="true" :model="filters" :size="size">
        <el-form-item label="姓名" prop="name">
          <el-input
            v-model="filters.name"
            placeholder="名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="filters.status" placeholder="请选择" clearable>
            <el-option
              v-for="item in statusOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学期" prop="termId">
          <el-select v-model="filters.termId" placeholder="请选择" clearable>
            <el-option
              v-for="item in termOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级" prop="deptName">
          <popup-tree-input
            :data="deptData"
            :props="deptTreeProps"
            :prop="filters.deptName"
            :nodeKey="'' + filters.deptId"
            :currentChangeHandle="deptTreeCurrentChangeHandle"
          >
          </popup-tree-input>
        </el-form-item>

        <el-form-item>
          <kt-button
            :label="$t('action.search')"
            perms="sys:busMoral:view"
            type="primary"
            @click="findPage(null)"
          />
        </el-form-item>
        <el-form-item>
          <kt-button
            :label="$t('action.searchTo')"
            perms="sys:busMoral:view"
            type="primary"
            @click="findPageTo(null)"
          />
        </el-form-item>
        <el-form-item>
          <kt-button
            :label="$t('action.add')"
            perms="sys:busMoral:add"
            type="primary"
            @click="handleAdd"
          />
        </el-form-item>
        <el-form-item>
          <kt-button
            :label="$t('action.import')"
            perms="sys:busMoral:import"
            type="primary"
            @click="handleImport"
          />
        </el-form-item>
        <el-form-item>
          <kt-button
            :label="$t('action.export')"
            perms="sys:busMoral:export"
            type="primary"
            @click="handleExport"
          />
        </el-form-item>
        <el-form-item>
          <kt-button
            :label="$t('action.calculation')"
            perms="sys:busMoral:calculation"
            type="primary"
            @click="handleCalculation"
          />
        </el-form-item>
        <el-form-item>
          <kt-button
            :label="$t('action.clear')"
            perms="sys:busMoral:clear"
            type="primary"
            @click="handleClear"
          />
        </el-form-item>
      </el-form>
    </div>
    <!--表格内容栏-->
    <kt-table
      permsEdit="sys:busMoral:edit"
      permsAuditStart="sys:busMoral:auditstart"
      permsAudit="sys:busMoral:audit"
      permsUploadFile="sys:busMoral:upload"
      permsView="sys:busMoral:view"
      :showAuditB="showAuditB"
      :pageType="pageType"
      permsDelete="sys:busMoral:delete"
      :data="pageResult"
      :columns="columns"
      @findPage="findPage"
      @handleEdit="handleEdit"
      @handleDelete="handleDelete"
    >
    </kt-table>
    <!--新增编辑界面-->
    <el-dialog
      :title="operation ? '新增' : '编辑'"
      width="40%"
      :visible.sync="editDialogVisible"
      :close-on-click-modal="false"
    >
      <el-form
        :model="dataForm"
        label-width="80px"
        :rules="dataFormRules"
        ref="dataForm"
        :size="size"
      >
        <el-form-item label="学号" prop="studentNum">
          <el-select
            v-model="dataForm.studentNum"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in userOptions"
              :key="item.name"
              :label="item.nickName"
              :value="item.name"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学期id" prop="termId">
          <el-select
            v-model="dataForm.termId"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in termOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="基本分" prop="moralC">
          <el-input v-model="dataForm.moralC" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="宿舍分" prop="moralD">
          <el-input v-model="dataForm.moralD" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="其他" prop="moralE">
          <el-input v-model="dataForm.moralE" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="测评分" prop="moralF">
          <el-input v-model="dataForm.moralF" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :size="size" @click.native="editDialogVisible = false">{{
          $t("action.cancel")
        }}</el-button>
        <el-button
          :size="size"
          type="primary"
          @click.native="submitForm"
          :loading="editLoading"
          >{{ $t("action.submit") }}</el-button
        >
      </div>
    </el-dialog>
    <!-- 导入成绩弹框，选择学期 -->
    <el-dialog
      class="login-resetPwd"
      title="导入成绩"
      :visible.sync="importDialogVisible"
      width="30%"
      s
    >
      <el-form
        :model="importInline"
        ref="importInline"
        label-position="left"
        label-width="100px"
        class="demo-ruleForm login-container"
      >
        <el-form-item label="学期id" prop="termId">
          <el-select
            v-model="importInline.termId"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in termOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文件名称" class="file-line" prop="fileName">
          <el-input
            :readonly="true"
            v-model="importInline.fileName"
            placeholder="文件名称"
          ></el-input>
          <el-upload
            style="display: inline-block; margin: 0 10px"
            action="string"
            :show-file-list="false"
            :http-request="uploadImgImport"
            :before-upload="beforeFirstAvatarUploadexcel"
            title="导入"
          >
            <el-button type="primary" class="tableBtn">选择文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="importDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="importFile">导 入</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import KtTable from "@/views/Core/KtTable";
import KtButton from "@/views/Core/KtButton";
import { format } from "@/utils/datetime";
import PopupTreeInput from "@/components/PopupTreeInput";
export default {
  components: {
    KtTable,
    KtButton,
    PopupTreeInput,
  },
  data() {
    return {
      size: "small",
      pageType: 2,
      filters: {
        name: "",
        deptId: "",
        deptName: "",
        termId: "",
        status: "",
      },
      columns: [
        { prop: "studentNum", label: "学号", minWidth: 100 },
        { prop: "username", label: "姓名", minWidth: 100 },
        { prop: "termname", label: "学期", minWidth: 100 },
        { prop: "deptname", label: "班级", minWidth: 100 },
        { prop: "moralC", label: "基本分", minWidth: 100 },
        { prop: "moralD", label: "宿舍分", minWidth: 100 },
        { prop: "moralE", label: "其他", minWidth: 100 },
        { prop: "moralF", label: "测评分", minWidth: 100 },
        { prop: "moralTotal", label: "总分", minWidth: 100 },
        { prop: "moralOrder", label: "排名", minWidth: 100 },
        {
          prop: "status",
          label: "状态",
          minWidth: 100,
          formatter: this.statusFormat,
        },
      ],
      pageRequest: { pageNum: 1, pageSize: 8 },
      pageResult: {},

      operation: false, // true:新增, false:编辑
      editDialogVisible: false, // 新增编辑界面是否显示
      editLoading: false,
      dataFormRules: {
        label: [{ required: true, message: "请输入名称", trigger: "blur" }],
      },
      // 新增编辑界面数据
      dataForm: {
        id: null,
        studentNum: null,
        termId: null,
        moralC: null,
        moralD: null,
        moralE: null,
        moralF: null,
        moralTotal: null,
        moralOrder: null,
      },
      termOptions: [],
      userOptions: [],
      //保存上传文件流
      itemFile: {},
      importDialogVisible: false,
      importInline: {
        termId: null,
        fileName: null,
      },
      deptData: [],
      deptTreeProps: {
        label: "name",
        children: "children",
      },
      showAuditB: true,
      statusOptions: [
        { id: 1, name: "未提交" },
        { id: 2, name: "班管退回" },
        { id: 3, name: "待班管审核" },
        { id: 4, name: "院管退回" },
        { id: 5, name: "待院管审核" },
        { id: 6, name: "审核完成" },
      ],
    };
  },
  methods: {
    // 获取分页数据
    async findPage(data) {
      await this.$api.busTerm.findCurrentTerm().then((res) => {
        if (!this.filters.termId || this.filters.termId == "") {
          this.$set(this.filters, "termId", res.data.id);
        }
      });
      if (data !== null) {
        this.pageRequest = data.pageRequest;
      }
      this.pageRequest.params = [
        { name: "name", value: this.filters.name },
        { name: "deptId", value: this.filters.deptId },
        { name: "termId", value: this.filters.termId },
        { name: "status", value: this.filters.status },
      ];
      await this.$api.busMoral
        .findPage(this.pageRequest)
        .then((res) => {
          if (res.code != 500) {
            this.pageResult = res.data;
          }
        })
        .then(data != null ? data.callback : "");
    },
    findPageTo: function (data) {
      if (data !== null) {
        this.pageRequest = data.pageRequest;
      }
      this.pageRequest.params = [
        { name: "name", value: this.filters.name },
        { name: "deptId", value: this.filters.deptId },
        { name: "termId", value: this.filters.termId },
        { name: "status", value: this.filters.status },
      ];
      this.$api.busMoral
        .findPageTo(this.pageRequest)
        .then((res) => {
          this.pageResult = res.data;
        })
        .then(data != null ? data.callback : "");
    },
    // 批量删除
    handleDelete: function (data) {
      this.$api.busMoral
        .batchDelete(data.params)
        .then(data != null ? data.callback : "");
    },
    // 显示新增界面
    handleAdd: function () {
      this.editDialogVisible = true;
      this.operation = true;
      this.dataForm = {
        id: null,
        studentNum: null,
        termId: null,
        moralC: null,
        moralD: null,
        moralE: null,
        moralF: null,
        moralTotal: null,
        moralOrder: null,
      };
    },
    // 显示编辑界面
    handleEdit: function (params) {
      this.editDialogVisible = true;
      this.operation = false;
      this.dataForm = Object.assign({}, params.row);
    },
    // 编辑
    submitForm: function () {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            this.editLoading = true;
            let params = Object.assign({}, this.dataForm);
            this.$api.busMoral.save(params).then((res) => {
              if (res.code == 200) {
                this.$message({ message: "操作成功", type: "success" });
              } else {
                this.$message({
                  message: "操作失败, " + res.msg,
                  type: "error",
                });
              }
              this.editLoading = false;
              this.$refs["dataForm"].resetFields();
              this.editDialogVisible = false;
              this.findPage(null);
            });
          });
        }
      });
    },
    // 时间格式化
    dateFormat: function (row, column, cellValue, index) {
      return format(row[column.property]);
    },
    // 状态格式化
    statusFormat: function (row, column, cellValue, index) {
      if (row.status == 1) {
        return "待提交";
      } else if (row.status == 2) {
        return "班管退回";
      } else if (row.status == 3) {
        return "班管审核中";
      } else if (row.status == 4) {
        return "院管退回";
      } else if (row.status == 5) {
        return "院管审核中";
      } else if (row.status == 6) {
        return "完成";
      }
    },
    getTermOptions: function () {
      this.$api.busTerm.findOptions(0).then((res) => {
        this.termOptions = res.data;
      });
    },
    getUserOptions: function () {
      this.$api.user.findUserOptions().then((res) => {
        this.userOptions = res.data;
      });
    },
    uploadImgImport(item) {
      this.itemFile = item.file;
    },
    // 导入事件
    beforeFirstAvatarUploadexcel(file) {
      let termId = this.importInline.termId;
      if (!termId) {
        this.$message.error("请选择导入的学期");
      }
      console.log(file);
      const isEXECL =
        file.type === `application/vnd.ms-excel` ||
        file.type ===
          `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`;
      if (!isEXECL) {
        this.$message.error("请导入正确的格式");
      }
      if (termId && isEXECL) {
        this.importInline.fileName = file.name;
      }
      return termId && isEXECL;
    },
    handleImport() {
      this.importDialogVisible = true;
    },
    importFile() {
      let formData = new FormData();
      formData.append("file", this.itemFile);
      formData.append("termId", this.importInline.termId);
      this.$api.busMoral.importSports(formData).then((res) => {
        this.editDialogVisible = false;
        this.findPage(null);
      });
    },
    // 获取部门列表
    findDeptTree: function () {
      this.$api.dept.findDeptTree().then((res) => {
        this.deptData = res.data;
      });
    },
    // 菜单树选中
    deptTreeCurrentChangeHandle(data, node) {
      this.filters.deptId = data.id;
      this.filters.deptName = data.name;
    },
    //导出
    handleExport() {
      if (this.filters.deptId == "" || this.filters.termId == "") {
        this.$message.error("请选择导出的学期和班级");
      } else {
        this.$api.busMoral.exportMoral(this.filters).then((data) => {
          //let fileName = data.headers['content-disposition'].slice(data.headers['content-disposition'].indexOf('=') + 1)
          let fileName = new Date().valueOf() + "-德育.xlsx";
          //let type = data.headers[`content-type`].slice(0, data.headers[`content-type`].indexOf(';'))
          let blob = new Blob([data]);
          if ("download" in document.createElement("a")) {
            // 非IE下载
            const elink = document.createElement("a");
            elink.setAttribute("download", decodeURI(fileName));
            elink.style.display = "none";
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            URL.revokeObjectURL(elink.href); // 释放 URL对象
            document.body.removeChild(elink);
          } else {
            // IE10+下载
            navigator.msSaveBlob(blob, fileName);
          }
        });
      }
    },
    handleCalculation() {
      if (this.filters.deptId == "" || this.filters.termId == "") {
        this.$message.error("请选择计算的学期和班级");
      } else {
        this.$api.busMoral.calculationSports(this.filters).then((data) => {
          this.findPage(null);
        });
      }
    },
    handleClear() {
      if (this.filters.deptId == "" || this.filters.termId == "") {
        this.$message.error("请选择清空的学期和班级");
      } else {
        this.$api.busMoral.resetSports(this.filters).then((data) => {
          this.findPage(null);
        });
      }
    },
    async findCurrentTerm() {
      await this.$api.busTerm.findCurrentTerm().then((res) => {
        this.$set(this.filters, "termId", res.data.id);
      });
    },
  },
  mounted() {
    this.findCurrentTerm();
    this.getTermOptions();
    this.getUserOptions();
    this.findDeptTree();
  },
};
</script>

<style scoped>
</style>
